package org.neu.ccs.secureim;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;

import org.apache.commons.codec.binary.Base64;

/*
 * Generate public/private keypair and store them in .properties files for the client/server
 */
public class keygen {

	/**
	 * @param args
	 */
	public static void main(String[] args) {		
		KeyPairGenerator generator = null;
		try {
			generator = KeyPairGenerator.getInstance("RSA");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			System.exit(-1);
		}
		
		generator.initialize(2048);
		KeyPair pair = generator.generateKeyPair();
		
		byte[] publicKey = pair.getPublic().getEncoded();
		byte[] privateKey = pair.getPrivate().getEncoded();
		
		Properties clientProperties = new Properties();
		Properties serverProperties = new Properties();
		
		clientProperties.put("ServerPubKey", Base64.encodeBase64String(publicKey));
		clientProperties.put("ServerAddress", "localhost");
		clientProperties.put("ServerPort", new Integer(7070).toString());
		serverProperties.put("ServerPrivateKey", Base64.encodeBase64String(privateKey));
		serverProperties.put("ServerPubKey", Base64.encodeBase64String(publicKey));
		serverProperties.put("ServerPort", new Integer(7070).toString());
		
		FileOutputStream out = null;
		try {
			out = new FileOutputStream("ServerSettings.properties" );
			serverProperties.store(out, "Settings for secure chat server");
			out.close();
			out = new FileOutputStream("ClientSettings.properties");
			clientProperties.store(out, "Settings for secure chat client");
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.exit(-1);
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(-1);
		}
	}

}
